<template>
  <div class="house-publish">
    <el-container>
      <el-main>
        <el-card class="publish-card">
          <template #header>
            <div class="card-header">
              <h2>{{ isEdit ? '编辑房源' : '发布房源' }}</h2>
            </div>
          </template>
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="publish-form"
          >
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入房源标题" />
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="form.price"
                :min="0"
                :precision="2"
                :step="100"
                placeholder="请输入月租金"
              />
              <span class="unit">元/月</span>
            </el-form-item>
            <el-form-item label="面积" prop="area">
              <el-input-number
                v-model="form.area"
                :min="0"
                :step="1"
                placeholder="请输入面积（平方米）"
              />
              <span class="unit">平方米</span>
            </el-form-item>
            <el-form-item label="户型" prop="type">
              <el-select v-model="form.type" placeholder="请选择户型">
                <el-option label="一室一厅" value="1" />
                <el-option label="两室一厅" value="2" />
                <el-option label="三室一厅" value="3" />
                <el-option label="三室两厅" value="3-2" />
                <el-option label="四室两厅" value="4-2" />
              </el-select>
            </el-form-item>
            <el-form-item label="省市" prop="region">
              <el-cascader
                v-model="form.region"
                :options="regionOptions"
                placeholder="请选择省市"
                :props="{ value: 'value', label: 'label', children: 'children' }"
                clearable
                style="width: 100%"
                @change="handleRegionChange"
                :disabled="regionLoading"
              />
              <div v-if="regionLoading" class="region-loading">
                正在加载省市数据...
              </div>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址（街道、小区、门牌号等）" />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="4"
                placeholder="请输入房源描述"
              />
            </el-form-item>
            <el-form-item label="附件" prop="images">
              <div class="upload-section">
                <el-upload
                  action="/api/upload"
                  list-type="picture-card"
                  :file-list="fileList"
                  :on-preview="handleFilePreview"
                  :on-remove="handleFileRemove"
                  :on-success="handleUploadSuccess"
                  :before-upload="beforeUpload"
                  :limit="8"
                  multiple
                  accept="image/*,video/*"
                  class="attachment-upload"
                >
                  <el-icon><Plus /></el-icon>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持图片（JPG、PNG、GIF）和视频（MP4、AVI、MOV等）文件，单个文件不超过50MB
                    </div>
                  </template>
                  
                  <!-- 自定义文件显示 -->
                  <template #file="{ file }">
                    <div class="upload-file-item">
                      <div class="file-thumbnail">
                        <!-- 图片预览 -->
                        <img 
                          v-if="isImageFile(file)" 
                          class="el-upload-list__item-thumbnail" 
                          :src="file.url" 
                          alt="" 
                        />
                        <!-- 视频文件显示默认图标 -->
                        <div v-else class="video-thumbnail">
                          <el-icon size="40" class="video-icon"><VideoPlay /></el-icon>
                          <span class="file-type">{{ getFileExtension(file.name || file.url) }}</span>
                        </div>
                      </div>
                      
                      <!-- 文件操作按钮 -->
                      <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handleFilePreview(file)">
                          <el-icon><ZoomIn /></el-icon>
                        </span>
                        <span class="el-upload-list__item-delete" @click="handleFileRemove(file)">
                          <el-icon><Delete /></el-icon>
                        </span>
                      </span>
                    </div>
                  </template>
                </el-upload>
                
                <!-- 文件预览对话框 -->
                <el-dialog v-model="dialogVisible" :title="currentFile.type === 'video' ? '视频预览' : '图片预览'" width="80%">
                  <div class="file-preview">
                    <img 
                      v-if="currentFile.type === 'image'" 
                      :src="currentFile.url" 
                      alt="Preview Image" 
                      class="preview-image"
                    />
                    <video 
                      v-else-if="currentFile.type === 'video'" 
                      :src="currentFile.url" 
                      controls 
                      class="preview-video"
                    >
                      您的浏览器不支持视频播放
                    </video>
                  </div>
                </el-dialog>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSubmit" round>
                {{ isEdit ? '保存修改' : '发布房源' }}
              </el-button>
              <el-button @click="handleCancel" round>取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, VideoPlay, Delete, ZoomIn } from '@element-plus/icons-vue'
import { houseApi } from '../api'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const isEdit = ref(false)

// 表单数据
const form = reactive({
  title: '',
  price: 0,
  area: 0,
  type: '',
  region: [],
  province_id: null,
  city_id: null,
  address: '',
  description: '',
  images: []
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入房源标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入月租金', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择户型', trigger: 'change' }
  ],
  region: [
    { required: true, message: '请选择省市', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入房源描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  images: [
    { required: true, message: '请上传至少一个附件', trigger: 'change' }
  ]
}

const dialogVisible = ref(false)
const fileList = ref([])
const currentFile = ref({ url: '', type: 'image' })
const regionLoading = ref(false)
const regionOptions = ref([])

// 获取省市级联数据
const fetchRegionData = async () => {
  try {
    regionLoading.value = true
    const response = await fetch('/api/regions/cascader', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error('获取省市数据失败')
    }
    
    const data = await response.json()
    regionOptions.value = data.regions
  } catch (error) {
    console.error('获取省市数据失败:', error)
    ElMessage.error('获取省市数据失败')
  } finally {
    regionLoading.value = false
  }
}

// 处理省市选择
const handleRegionChange = (value) => {
  if (value && value.length === 2) {
    form.province_id = value[0]
    form.city_id = value[1]
  } else {
    form.province_id = null
    form.city_id = null
  }
}

// 处理文件预览
const handleFilePreview = (file) => {
  currentFile.value = {
    url: file.url,
    type: getFileType(file.url || file.name)
  }
  dialogVisible.value = true
}

// 判断文件类型
const getFileType = (filename) => {
  const ext = filename.split('.').pop().toLowerCase()
  if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) {
    return 'image'
  } else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'].includes(ext)) {
    return 'video'
  }
  return 'unknown'
}

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isVideo = file.type.startsWith('video/')
  const isValidType = isImage || isVideo
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isValidType) {
    ElMessage.error('只能上传图片或视频文件！')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB！')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  form.images.push(response.url)
  ElMessage.success('文件上传成功')
}

// 处理文件移除
const handleFileRemove = (file) => {
  console.log(file)
  console.log(form.images)
  const index = form.images.findIndex(img => img === file.url)
  if (index !== -1) {
    form.images.splice(index, 1)
  }
  // 强制刷新
  fileList.value = fileList.value.filter(item => item.url !== file.url)
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          title: form.title,
          price: form.price,
          area: form.area,
          type: form.type,
          province_id: form.province_id,
          city_id: form.city_id,
          address: form.address,
          description: form.description,
          images: form.images
        }
        
        if (isEdit.value) {
          await houseApi.updateHouse(route.params.id, submitData)
          ElMessage.success('修改成功')
        } else {
          await houseApi.createHouse(submitData)
          ElMessage.success('发布成功')
        }
        router.push('/user')
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

// 处理取消
const handleCancel = () => {
  router.back()
}

// 如果是编辑模式，获取房源信息
if (route.params.id) {
  isEdit.value = true
  const fetchHouseDetail = async () => {
    try {
      const data = await houseApi.getHouseDetail(route.params.id)
      const houseData = data.house
      
      // 填充表单数据
      Object.assign(form, {
        title: houseData.title,
        price: houseData.price,
        area: houseData.area,
        type: houseData.type,
        province_id: houseData.province_id,
        city_id: houseData.city_id,
        address: houseData.address,
        description: houseData.description,
        images: houseData.images || []
      })
      
      // 设置省市级联选择器的值
      if (houseData.province_id && houseData.city_id) {
        form.region = [houseData.province_id, houseData.city_id]
      }
      
      // 设置文件列表以显示现有附件
      fileList.value = (houseData.images || []).map((url, index) => ({
        name: `attachment-${index}`,
        url: url,
        uid: index
      }))
    } catch (error) {
      ElMessage.error('获取房源信息失败')
      router.push('/user')
    }
  }
  
  // 等待省市数据加载完成后再加载房源详情
  onMounted(async () => {
    await fetchRegionData()
    await fetchHouseDetail()
  })
} else {
  // 非编辑模式，只需要加载省市数据
  onMounted(() => {
    fetchRegionData()
  })
}

// 判断文件是否为图片
const isImageFile = (file) => {
  const filename = file.name || file.url || ''
  const ext = filename.split('.').pop()?.toLowerCase() || ''
  return ['jpg', 'jpeg', 'png', 'gif'].includes(ext)
}

// 获取文件扩展名
const getFileExtension = (filename) => {
  if (!filename) return 'FILE'
  const ext = filename.split('.').pop()?.toLowerCase() || ''
  return ext.toUpperCase()
}
</script>

<style scoped>
.house-publish {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e3f0ff 100%);
  padding: 24px;
}

.publish-card {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(64,158,255,0.08);
  background: #fff;
  animation: fadeInUp 0.5s;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.publish-form {
  margin-top: 20px;
}

.el-input-number {
  width: 200px;
}

.unit {
  margin-left: 10px;
  color: #909399;
}

/* 附件上传区域样式 */
.upload-section {
  width: 100%;
}

.attachment-upload {
  width: 100%;
}

.el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 120px;
  border-radius: 8px;
}

.el-upload__tip {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
}

/* 文件预览样式 */
.file-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 8px;
}

.preview-video {
  max-width: 100%;
  max-height: 70vh;
  border-radius: 8px;
}

/* 动画效果 */
@keyframes fadeInUp {
  0% { 
    opacity: 0; 
    transform: translateY(40px); 
  }
  100% { 
    opacity: 1; 
    transform: translateY(0); 
  }
}

/* 响应式设计 */
@media (max-width: 600px) {
  .house-publish { 
    padding: 12px; 
  }
  
  .el-input-number { 
    width: 100%; 
  }
  
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  
  .preview-image,
  .preview-video {
    max-height: 50vh;
  }
}

/* 上传列表项样式优化 */
:deep(.el-upload-list__item) {
  transition: all 0.3s ease;
}

:deep(.el-upload-list__item:hover) {
  transform: scale(1.05);
}

/* 上传进度条样式 */
:deep(.el-progress) {
  margin-top: 8px;
}

/* 文件类型标识 */
:deep(.el-upload-list__item-thumbnail) {
  object-fit: cover;
}

/* 自定义文件显示样式 */
.upload-file-item {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.file-thumbnail {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-thumbnail {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  text-align: center;
}

.video-icon {
  margin-bottom: 8px;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
}

.file-type {
  font-size: 12px;
  font-weight: bold;
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 4px;
  backdrop-filter: blur(5px);
}

/* 文件操作按钮样式优化 */
.el-upload-list__item-actions {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
  border-radius: 8px;
}

.upload-file-item:hover .el-upload-list__item-actions {
  opacity: 1;
}

.el-upload-list__item-preview,
.el-upload-list__item-delete {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  margin: 0 4px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
}

.el-upload-list__item-preview:hover {
  background: #409EFF;
  color: white;
  transform: scale(1.1);
}

.el-upload-list__item-delete:hover {
  background: #F56C6C;
  color: white;
  transform: scale(1.1);
}

/* 省市选择器样式 */
.region-loading {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

.el-cascader {
  width: 100%;
}

/* 级联选择器下拉面板样式优化 */
:deep(.el-cascader-panel) {
  border-radius: 8px;
}

:deep(.el-cascader-node) {
  transition: all 0.3s ease;
}

:deep(.el-cascader-node:hover) {
  background-color: #f5f7fa;
}
</style> 